package bicing;
import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import storage.KMLDocument;

@SuppressWarnings("serial")
public class PublicServlet extends HttpServlet {
	private final static PersistenceManager persistenceManager = PersistenceManagerSingleton.getPersistenceManager();
	private final static String QUERY = "SELECT FROM " + KMLDocument.class.getName() + " WHERE id == 'BICING'";
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
		resp.setContentType("text/xml");
		resp.setHeader("Content-Disposition", "attachment; filename=bicing.kml");
		try{
				List<KMLDocument> result = (List<KMLDocument>) persistenceManager.newQuery(QUERY).execute();
				if(result.size() > 0){
					KMLDocument kmlDocument = result.get(0);
					resp.getWriter().write(kmlDocument.getKml());
				}else{
					throw new ServletException("No kml found!");
				}
		} catch (IOException e) {
			throw new ServletException(e);
		}
	}
}
